package com.java.servlet.web.conexion;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class PoolConnection {

	private static PoolConnection instance = null;
	private DataSource dataSource;
	private static final Logger log = Logger.getLogger(PoolConnection.class);	
	Context ctx = null;
	private PoolConnection() {
		/**
		 * Lineas para integrar la coneccion atravez de JNDI. Esta configuracion esta en context.xml del server.
		 */
		try {
			ctx = new InitialContext();
			dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyLocalDB");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	    /**
	     * Quitar el comentario para realizar pruebas con el pool de conecciones configurado en esta clase
	     */
	    /*
		dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost:3306/ros_desarrollo");
		dataSource.setUsername("root");
		dataSource.setPassword("meltsan");
		*/
	}
	public static PoolConnection getInstance() {
		if (instance == null) {
			instance = new PoolConnection();
		}
		return instance;
	}

	public Connection getConection() {
		Connection con = null;
		try {
			con = dataSource.getConnection();
		} catch (SQLException ex) {
			log.error("getConection [ " + ex);
		}
		return con;
	}
    public void closeConnection(Connection conexion) {
        try {
            if (conexion != null && !conexion.isClosed()) {
                conexion.close();
            }
        } catch (SQLException ex) {
        	log.error("closeConnection [ " + ex);
        }
    }

    public void beginTransaction(Connection con) {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(false);
            }
        } catch (SQLException ex) {
        	log.error("beginTransaction [ " + ex);
        }
    }
    public void endTransaction(Connection con) {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
            }
        } catch (SQLException ex) {
        	log.error("endTransaction [ " + ex);
        }
    }

    public void commit(Connection con) {
        try {
            if (con != null && !con.isClosed()) {
                con.commit();
            }
        } catch (SQLException ex) {
        	log.error("commit [ " + ex);
        }
    }

    public void rollback(Connection con) {
        try {
            if (con != null && !con.isClosed()) {
                con.rollback();
            }
        } catch (SQLException ex) {
        	log.error("rollback [ " + ex);
        }
    }
}
